<template>
    <t-layout>
        <t-header>
            <t-space>
                <t-select v-model="selected_config.grade" label="年级">
                    <t-option value="all">
                        【所有年级】
                    </t-option>
                    <t-option v-for="grade in available_config.grade" :value="grade">
                        {{ grade }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.subject" label="学科">
                    <t-option value="all">
                        【所有学科】
                    </t-option>
                    <t-option v-for="subject in available_config.subjects" :value="subject">
                        {{ subject }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.class_name" label="班级">
                    <t-option value="all">
                        【所有班级】
                    </t-option>
                    <t-option v-for="class_name in available_config.class_names" :value="class_name">
                        {{ class_name }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.date" label="时间">
                    <t-option value="all">
                        【所有时间】
                    </t-option>
                    <t-option value="today">
                        今天应复习
                    </t-option>
                    <t-option value="tomorrow">
                        明天应复习
                    </t-option>
                </t-select>
            </t-space>
        </t-header>
        <t-content style="margin: auto;width:70%">
            <t-switch v-model="sort_by_due"></t-switch><span>按下次复习时间排序</span>
            <t-switch v-model="review_in_yesterday"></t-switch><span>复习时间改为昨天</span>
            <t-alert theme="info" message="请在上方选择年级、班级、科目、时间" v-if="showSkeleton" />
            <t-skeleton :loading="showSkeleton">
                <t-alert theme="success" message="今日已复习完！" v-if="noCard" />
                <div class="card" v-else>
                    <t-space>
                        <t-switch v-model="showAnswer" />显示答案
                        <t-button variant="outline" @click="handleBatchReview">
                            <template #icon><thumb-up-2-filled-icon /></template>
                            一键点【好】
                        </t-button>
                        <t-button variant="outline" @click="copyCardsToClipboard1">
                            <template #icon><copy-icon /></template>
                            复制题目
                        </t-button>
                        <t-button variant="outline" @click="copyCardsToClipboard2">
                            <template #icon><copy-icon /></template>
                            复制题目和答案
                        </t-button>
                    </t-space>
                    <br />
                    *您可以先把复习效果不好的条目点击“<thumb-down2-icon />”,然后把剩下的闪卡一键点好
                    <br />
                    *为了更好的复习效果，请在复习完后对每个条目进行反馈，点击<thumb-up2-icon />表示记忆尚可，点击<thumb-down2-icon />表示记忆不佳
                    <t-divider />
                    <t-space align="center">
                        <t-icon name="chart" class="icon" />
                        <t-statistic title="总闪卡数" :value="cards.length" />
                    </t-space>
                    <t-divider />
                    <t-collapse>
                        <t-collapse-panel header="卡片预览">
                            <div id="card-thumbs">
                                <span v-for="card_text in cards_text" style="padding:5px ;margin-top: 5px;">
                                    <colored-tag-component :text="card_text"></colored-tag-component>
                                </span>
                            </div>
                        </t-collapse-panel>
                    </t-collapse>
                    <t-divider />
                    <t-list v-for="(card, index) in cards" :key="card.id" class="card-list"
                        :class="{ 'selected-card': selectedIndex === index }">
                        <div class="card-block">
                            <t-list-item class="question">
                                <div>{{ card.question }}</div>
                                <template #action>
                                    <t-button variant="text" shape="square" @click="() => handleReview(card.id, 3)">
                                        <thumb-up-2-icon />
                                    </t-button>
                                    <t-button variant="text" shape="square" @click="() => handleReview(card.id, 1)">
                                        <thumb-down-2-icon />
                                    </t-button>
                                </template>
                            </t-list-item>
                            <t-list-item class="answer">
                                <div style="font-size: 0.5em;">上次复习时间：{{ convertUtcToLocal(card.last_review) }}</div>
                                <span v-if="showAnswer">
                                    {{ card.answer }}
                                </span>
                                <span v-else class="icon-container">
                                    <svg class="icon" viewBox="0 0 1024 1024" width="1em" height="1em">
                                        <path
                                            d="M872.18176 507.98592l-42.5984-59.02336c12.36992-9.85088 24.65792-20.25472 36.864-31.25248 6.7584-6.08256 7.41376-16.62976 1.49504-23.552-5.9392-6.92224-16.22016-7.61856-22.97856-1.51552-83.57888 75.264-170.92608 122.14272-259.62496 139.32544-70.63552 13.68064-142.52032 8.68352-213.62688-14.848-63.75424-21.0944-115.13856-53.49376-147.0464-76.94336-34.44736-25.33376-54.23104-46.01856-54.76352-46.592-6.2464-6.63552-16.54784-6.81984-23.01952-0.4096-6.47168 6.41024-6.63552 16.97792-0.38912 23.59296 0.73728 0.77824 16.0768 16.95744 43.68384 38.68672l-38.33856 50.74944c-5.50912 7.29088-4.1984 17.77664 2.90816 23.40864 2.9696 2.3552 6.47168 3.50208 9.95328 3.50208 4.85376 0 9.68704-2.23232 12.88192-6.47168l38.95296-51.58912c28.63104 20.04992 68.4032 44.11392 116.24448 63.24224l-25.82528 57.15968c-3.76832 8.35584-0.22528 18.28864 7.92576 22.15936 2.21184 1.04448 4.54656 1.55648 6.84032 1.55648 6.144 0 12.02176-3.584 14.78656-9.66656l27.11552-60.0064c42.20928 13.78304 84.6848 21.48352 127.05792 23.06048l0 63.54944c0 9.216 7.29088 16.6912 16.2816 16.6912 8.99072 0 16.2816-7.4752 16.2816-16.6912l0-63.52896c22.50752-0.8192 44.97408-3.3792 67.31776-7.65952 23.94112-4.58752 47.75936-11.18208 71.41376-19.7632l28.5696 60.84608c2.80576 5.98016 8.62208 9.46176 14.68416 9.46176 2.3552 0 4.77184-0.53248 7.04512-1.65888 8.11008-3.9936 11.50976-13.96736 7.61856-22.28224l-27.48416-58.53184c37.53984-16.40448 74.58816-37.82656 111.02208-64.16384l42.57792 59.00288c3.19488 4.42368 8.11008 6.7584 13.1072 6.7584 3.35872 0 6.7584-1.06496 9.66656-3.2768C876.01152 525.84448 877.52704 515.39968 872.18176 507.98592L872.18176 507.98592zM872.18176 507.98592"
                                            fill="#030000" p-id="1466">
                                        </path>
                                    </svg>
                                </span>

                            </t-list-item>
                        </div>
                    </t-list>
                </div>
            </t-skeleton>
        </t-content>
    </t-layout>
</template>
<script setup lang="jsx">
import { ThumbUp2Icon, ThumbDown2Icon, ThumbUp2FilledIcon, CopyIcon } from 'tdesign-icons-vue-next';
import { ref, onMounted, computed, onUnmounted, watch, onBeforeUnmount } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import ColoredTagComponent from '../components/ColoredTagComponent.vue'
import axios from 'axios'

// 从本地存储加载配置
const loadConfigFromStorage = () => {
    const savedConfig = localStorage.getItem('reviewConfig')
    return savedConfig ? JSON.parse(savedConfig) : { grade: '', subject: '', class_name: '', date: '' }
}

// 保存配置到本地存储
const saveConfigToStorage = (config) => {
    localStorage.setItem('reviewConfig', JSON.stringify(config))
}

const selected_config = ref(loadConfigFromStorage())
//判断是否显示骨架屏
const showSkeleton = computed(() => {
    return !selected_config.value.grade || !selected_config.value.subject || !selected_config.value.class_name || !selected_config.value.date;
})
const available_config = ref({ grades: [], subjects: [], class_names: [] })
const loadAvailableConfig = async () => {
    try {
        const response = await axios.get('/api/config')
        available_config.value = response.data
    } catch (error) {
        console.error('Error fetching config:', error)
        MessagePlugin.error('获取配置失败，请截图并发送给作者', error)
    }
}

// 添加选中索引用于键盘导航
const selectedIndex = ref(-1)

// 添加页面离开提示
const beforeUnloadHandler = (e) => {
    if (cards.value.length > 0) {
        e.preventDefault();
        e.returnValue = '请给所有闪卡做好标记';
        return '请给所有闪卡做好标记';//似乎没什么卵用，Edge显示为“您所做的更改可能未保存”
    }
};

onMounted(() => {
    document.title = '复习闪卡'
    loadAvailableConfig()
    window.addEventListener('beforeunload', beforeUnloadHandler)
    if (selected_config.value.grade && selected_config.value.subject &&
        selected_config.value.class_name && selected_config.value.date) {
        fetchCard()
    }
    window.addEventListener('keydown', handleKeyDown)
})

// 添加组件卸载时的清理
onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', beforeUnloadHandler)
})
onUnmounted(() => {
    // 移除键盘事件监听器
    window.removeEventListener('keydown', handleKeyDown)
})
const noCard = computed(() => {
    return cards.value.length == 0
})
const showAnswer = ref(false)
const sort_by_due = ref(true)
const cards = ref([])
const review_in_yesterday = ref(false)
function fetchCard() {
    const { grade, subject, class_name, date } = selected_config.value
    const sort_by_due_value = sort_by_due.value
    axios.get('/api/list_cards', { params: { grade, subject, class_name, date, sort_by_due_value } })
        .then(response => {
            if (response.status == 200) {
                cards.value = response.data.cards
                console.log('获取闪卡', cards.value)
            }
        })
}
// 当配置变化时获取卡片
watch(selected_config, (newVal) => {
    if (newVal.grade && newVal.subject && newVal.class_name && newVal.date) {
        fetchCard()
        saveConfigToStorage(newVal) // 保存配置到本地存储
    }
}, { deep: true })
const handleKeyDown = (event) => {
    // 只有当有卡片且未显示骨架屏时才处理键盘事件
    if (showSkeleton.value || noCard.value) return

    switch (event.key) {
        case 'ArrowUp':
            event.preventDefault()
            // 向上键，选中上一张卡片
            if (selectedIndex.value > 0) {
                selectedIndex.value--
                scrollToSelectedCard()
            }
            break
        case 'ArrowDown':
            event.preventDefault()
            // 向下键，选中下一张卡片
            if (selectedIndex.value < cards.value.length - 1) {
                selectedIndex.value++
                scrollToSelectedCard()
            }
            break
        case '1':
            event.preventDefault()
            // 按1键，相当于点击大拇指向下
            if (selectedIndex.value >= 0 && selectedIndex.value < cards.value.length) {
                handleReviewWithKeyboard(cards.value[selectedIndex.value].id, 1)
            }
            break
        case '3':
            event.preventDefault()
            // 按3键，相当于点击大拇指向上
            if (selectedIndex.value >= 0 && selectedIndex.value < cards.value.length) {
                handleReviewWithKeyboard(cards.value[selectedIndex.value].id, 3)
            }
            break
    }
}

// 滚动到选中的卡片
const scrollToSelectedCard = () => {
    setTimeout(() => {
        const selectedElement = document.querySelector('.selected-card')
        if (selectedElement) {
            selectedElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
    }, 0)
}

// 带键盘处理的复习函数
const handleReviewWithKeyboard = async (cardId, rating) => {
    try {
        const response = await axios.post('/api/review', {
            card_id: cardId,
            rating: rating
        })
        if (response.status === 200) {
            MessagePlugin.success('复习成功，下次时间：' + convertUtcToLocal(response.data.new_due))
            // 从卡片列表中移除该卡片
            const removedIndex = cards.value.findIndex(card => card.id === cardId)
            cards.value = cards.value.filter(card => card.id !== cardId)

            // 调整选中索引
            if (cards.value.length === 0) {
                // 如果没有卡片了，重置选中索引
                selectedIndex.value = -1
            } else if (removedIndex === selectedIndex.value) {
                // 如果删除的是当前选中的卡片，保持选中索引不变（会自动指向下一卡片）
                // 如果删除的是最后一张卡片，则选中索引减1
                if (selectedIndex.value >= cards.value.length) {
                    selectedIndex.value = cards.value.length - 1
                }
            } else if (removedIndex < selectedIndex.value) {
                // 如果删除的是前面的卡片，选中索引减1
                selectedIndex.value--
            }
            // 如果删除的是后面的卡片，选中索引不变

            // 确保选中索引有效
            if (selectedIndex.value < 0 && cards.value.length > 0) {
                selectedIndex.value = 0
            }
        }
    } catch (error) {
        console.error('提交复习记录失败:', error)
        MessagePlugin.error('提交复习记录失败')
    }
}

const handleReview = async (cardId, rating) => {
    try {
        const response = await axios.post('/api/review', {
            card_id: cardId,
            rating: rating,
            yesterday: review_in_yesterday.value
        })
        if (response.status === 200) {
            MessagePlugin.success('复习成功，下次时间：' + convertUtcToLocal(response.data.new_due))
            // 重新获取卡片列表
            cards.value = cards.value.filter(card => card.id !== cardId);
        }
    } catch (error) {
        console.error('提交复习记录失败:', error)
        MessagePlugin.error('提交复习记录失败')
    }
}

// 添加批量处理函数
const handleBatchReview = async () => {
    try {
        const promises = cards.value.map(card =>
            axios.post('/api/review', {
                card_id: card.id,
                rating: 3,
                yesterday: review_in_yesterday.value
            })
        );
        await Promise.all(promises);
        MessagePlugin.success(`已为${cards.value.length}张闪卡标记为"好"`);
        cards.value.length = 0
    } catch (error) {
        console.error('批量提交复习记录失败:', error);
        MessagePlugin.error('批量提交复习记录失败');
    }
}

const copyCardsToClipboard1 = () => {
    const today = new Date().toISOString().split('T')[0];
    let clipboardText = `${today}复习内容：\n\n`;

    cards.value.forEach(card => {
        clipboardText += `${card.question}\n`;
    });

    navigator.clipboard.writeText(clipboardText.trim())
        .then(() => MessagePlugin.success('已复制到剪贴板'))
        .catch(err => {
            console.error('复制失败:', err);
            MessagePlugin.error('复制失败');
        });
}

const copyCardsToClipboard2 = () => {
    const today = new Date().toISOString().split('T')[0];
    let clipboardText = `${today}复习内容：\n\n`;

    cards.value.forEach(card => {
        clipboardText += `${card.question}\n${card.answer}\n\n`;
    });

    navigator.clipboard.writeText(clipboardText.trim())
        .then(() => MessagePlugin.success('已复制到剪贴板'))
        .catch(err => {
            console.error('复制失败:', err);
            MessagePlugin.error('复制失败');
        });
}
function convertUtcToLocal(utcString) {
    if (!utcString) return '';
    const date = new Date(utcString + 'Z');
    const daysDiff = Math.round((date - new Date()) / (1000 * 60 * 60 * 24));
    return `${date.getMonth() + 1}月${date.getDate()}日(${Math.abs(daysDiff)}天${daysDiff > 0 ? '后' : '前'})`;
}

const cards_text = computed(() => {
    if (!cards.value || cards.value.length === 0) {
        return "";
    }

    // 处理第一个元素
    let result = [`${cards.value[0].subject} ${cards.value[0].grade} ${cards.value[0].question}`];

    // 处理后续元素
    for (let i = 1; i < cards.value.length; i++) {
        const prev = cards.value[i - 1];
        const curr = cards.value[i];

        if (prev.subject !== curr.subject) {
            // 学科不同：拼接 \t{subject} {grade} {question}
            result.push(`\t${curr.subject} ${curr.grade} ${curr.question}`);
        } else {
            if (prev.grade !== curr.grade) {
                // 学科相同但年级不同：拼接 \t{grade} {question}
                result.push(`\t${curr.grade} ${curr.question}`);
            } else {
                // 学科和年级都相同：拼接 \t{question}
                result.push(`\t${curr.question}`);
            }
        }
    }

    return result;
})
</script>

<style scoped>
.question {
    border-top: 3px solid #e5e5e5;
    font-size: 3em;
    font-family: "楷体", "楷体_GB2312";
}

.answer {
    font-size: 2em;
    font-family: "楷体", "楷体_GB2312";
}

.icon-container {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-left: 8px;
}

.icon {
    vertical-align: middle;
    fill: currentColor;
}

/* 添加卡片列表的固定宽度样式 */
.card-list {
    width: 100%;
    display: block;
}

.selected-card .card-block {
    border: 3px solid #007bff;
    border-radius: 8px;
    background-color: #f8f9fa;
}
</style>